﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;

namespace ZXW.DotNet.Common.DbUtilities
{
    public class ConnectionStringBuilder
    {
        private  IList<KeyValuePair<string, ConnectionStringStrategyBase>> _mStrategies;
        public virtual IList<KeyValuePair<string, ConnectionStringStrategyBase>> Strategies
        {
            get { return _mStrategies; }
        }

        public ConnectionStringBuilder(NameValueCollection collection)
        {
            _mStrategies = new List<KeyValuePair<string, ConnectionStringStrategyBase>>();
            foreach (string key in collection.Keys)
            {
                string typeNmae = collection[key];
                Type type = Type.GetType(typeNmae);
                ConnectionStringStrategyBase strategy = (ConnectionStringStrategyBase)Activator.CreateInstance(type);
                _mStrategies.Add(new KeyValuePair<string, ConnectionStringStrategyBase>(key, strategy));
            }
        }

        /// <summary>
        /// 获得连接串配置的副本
        /// 由于配置文件对象的内容是个进程内共享的机制
        /// </summary>
        /// <returns></returns>
        private IDictionary<string, ConnectionStringSettings> GetConnectionsCopy()
        {
            IDictionary<string, ConnectionStringSettings> result = new Dictionary<string, ConnectionStringSettings>();
            foreach (ConnectionStringSettings setting in ConfigurationManager.ConnectionStrings)
            {
                ConnectionStringSettings settingCopy = new ConnectionStringSettings(setting .Name ,
                    setting .ConnectionString ,
                    setting .ProviderName );
                result.Add(setting.Name, settingCopy);
            }
            return result;
        }

        /// <summary>
        /// 对连接串配置对象逐个处理后返回
        /// </summary>
        /// <returns></returns>
        public IDictionary<string, ConnectionStringSettings> BulidUp()
        {
            IDictionary<string, ConnectionStringSettings> result = GetConnectionsCopy();
            if ((Strategies != null) && (Strategies.Count > 0))
            {
                foreach (KeyValuePair<string, ConnectionStringStrategyBase> pair in Strategies)
                {
                    string name = pair.Key;
                    ConnectionStringSettings setting = result[name];
                    ConnectionStringStrategyBase strategy = pair.Value;
                    strategy.Process(ref setting);
                }
            }
            return result;
        }
    }
}
